﻿Imports Microsoft.AspNet.Membership.OpenAuth
Imports System.Data
Imports System.Data.SqlClient
Public Class Register
    Inherits Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Request.Browser.IsMobileDevice Then
            Response.Redirect("~/Account/Register_mobile.aspx")
        End If
        RegisterUser.ContinueDestinationPageUrl = Request.QueryString("ReturnUrl")
    End Sub

    Protected Sub RegisterUser_CreatedUser(ByVal sender As Object, ByVal e As EventArgs) Handles RegisterUser.CreatedUser
        FormsAuthentication.SetAuthCookie(RegisterUser.UserName, createPersistentCookie:=False)

        Dim continueUrl As String = RegisterUser.ContinueDestinationPageUrl
        If Not OpenAuth.IsLocalUrl(continueUrl) Then
            continueUrl = "~/"
        End If

        'Add user to Profiles table in database which stores the members.
        Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("BooksReviewDBConnectionString1").ConnectionString.ToString)
        Dim cmd As New SqlCommand("INSERT INTO Profiles(Bibliophile) VALUES (@f1)", conn)
        conn.Open()
        cmd.CommandType = CommandType.Text
        cmd.Parameters.AddWithValue("@f1", RegisterUser.UserName)
        cmd.ExecuteNonQuery()
        conn.Close()
        cmd.Dispose()

        'Create an empty entry in the Favorite_Book table which is used to store the favorite book of each member.
        'When a member chooses a favorite book this entry is updated
        Dim cmdFavBook As New SqlCommand("INSERT INTO Favorite_Book(Bibliophile) VALUES (@f1)", conn)

        cmdFavBook.CommandType = CommandType.Text
        cmdFavBook.Parameters.AddWithValue("@f1", RegisterUser.UserName)
        conn.Open()
        cmdFavBook.ExecuteNonQuery()
        conn.Close()
        cmdFavBook.Dispose()

        'Adding user to roles as bibliophile (The first rank in roles)
        Dim userName = RegisterUser.UserName
        Roles.AddUserToRole(userName, "bibliophile")
        'Redirect to EditProfile page so a member will add his details
        Response.Redirect("~/EditProfile.aspx")
    End Sub
End Class